package com.manor.main.login;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.lzy.okgo.model.Response;
import com.manor.common.CommonAppConfig;
import com.manor.common.Constants;
import com.manor.common.activity.AbsActivity;
import com.manor.common.activity.BaseLocationActivity;
import com.manor.common.bean.UserBean;
import com.manor.common.event.LoginSuccessEvent;
import com.manor.common.http.JHttpCallback;
import com.manor.common.http.JJsonBean;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.utils.GsonUtil;
import com.manor.common.utils.SpUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.main.R;
import com.manor.main.activity.LoginGenderAgeActivity;
import com.manor.main.activity.MainActivity;
import com.manor.main.bean.LoginBean;
import com.manor.main.http.JMainHttpUtil;
import com.manor.main.http.MainHttpUtil;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

/**
 * 注册登录首页
 */
public class LauncherLoginFragment extends Fragment implements View.OnClickListener {
    private Context mContext;
    private EditText etPhoneNumber, etPassword;
    public static final String AES_KEY = "MH_mohirds_dunan";
    public static final String AES_IV = "MH_mohirds_dasha";
    public static final String AES_TRANSFORM = "AES/CBC/PKCS5Padding";
    private boolean mFirstLogin;//是否是第一次登录.

    public LauncherLoginFragment() {

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    public static LauncherLoginFragment newInstance() {
        return new LauncherLoginFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_login_main, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.tv_register).setOnClickListener(this);
        view.findViewById(R.id.tv_forget_password).setOnClickListener(this);
        view.findViewById(R.id.tv_code_login).setOnClickListener(this);
        view.findViewById(R.id.btn_login).setOnClickListener(this);

        etPhoneNumber = view.findViewById(R.id.et_phone_number);
        etPassword = view.findViewById(R.id.et_password);
        TextView tvAgreement = view.findViewById(R.id.tv_agreement);
        if (mContext instanceof LoginActivity) {
            ((LoginActivity) mContext).dealAgreement(tvAgreement);
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();// 密码登录
        LoginActivity activity = (LoginActivity) mContext;
        if (id == R.id.btn_login) { // 密码注册
            String phoneNum = etPhoneNumber.getText().toString().trim();
            if (TextUtils.isEmpty(phoneNum)) {
                ToastUtil.show("请输入手机号");
                return;
            }
            if (!RegexUtils.isMatch(LoginActivity.REGEX_PHONE, phoneNum)) {
                ToastUtil.show("请输入11位手机号");
                return;
            }

            String password = etPassword.getText().toString().trim();
            if (TextUtils.isEmpty(password)) {
                ToastUtil.show("请输入密码");
                return;
            }
            if (!RegexUtils.isMatch(LoginActivity.REGEX_PSWD, password)) {
                ToastUtil.show("请输入密码长度为8-12位");
                return;
            }
            // 隐藏键盘
            if (KeyboardUtils.isSoftInputVisible((AbsActivity) mContext)) {
                KeyboardUtils.hideSoftInput((AbsActivity) mContext);
            }
            doLoginByPassword(phoneNum, password);
        } else if (id == R.id.tv_code_login) {
            // 验证码登录
            if (activity instanceof LoginActivity) {
                activity.loadCodeFragment();
            }
        } else if (id == R.id.tv_register || id == R.id.tv_forget_password) {
            // 隐藏键盘
            if (KeyboardUtils.isSoftInputVisible((AbsActivity) mContext)) {
                KeyboardUtils.hideSoftInput((AbsActivity) mContext);
            }
            if (mContext instanceof LoginActivity) {

                FragmentManager fragmentManager = activity
                        .getSupportFragmentManager();
                VCodeVerifyFragment vCodeFragment = (VCodeVerifyFragment) fragmentManager
                        .findFragmentByTag(VCodeVerifyFragment.class.getSimpleName());
                if (vCodeFragment == null) {
                    vCodeFragment = VCodeVerifyFragment.newInstance();
                }
                Bundle args = new Bundle();
                if (id == R.id.tv_register) {// 跳转到注册
                    args.putInt(VCodeVerifyFragment.FLAG_FROM_TYPE, 1);
                    args.putString(VCodeVerifyFragment.FLAG_TITLE_TEXT, "密码注册");
                    args.putString(VCodeVerifyFragment.FLAG_BTN_TEXT, "下一步");

                } else if (id == R.id.tv_forget_password) {  // 跳转到忘记密码
                    args.putInt(VCodeVerifyFragment.FLAG_FROM_TYPE, 3);
                    args.putString(VCodeVerifyFragment.FLAG_TITLE_TEXT, "忘记密码");
                    args.putString(VCodeVerifyFragment.FLAG_BTN_TEXT, "确认");
                }
                vCodeFragment.setArguments(args);

                FragmentTransaction ft = fragmentManager.beginTransaction();
                if (!vCodeFragment.isAdded()) {
                    ft.add(R.id.fl_container, vCodeFragment, VCodeVerifyFragment.class.getSimpleName());
                    ft.addToBackStack(VCodeVerifyFragment.class.getSimpleName());
                } else {
                    ft.show(vCodeFragment);
                }
                ft.commit();
            }
        }
    }

    /**
     * 登录
     */
    private void doLoginByPassword(String phoneNum, String password) {
        if (mContext instanceof LoginActivity) {
            LoginActivity activity = (LoginActivity) mContext;
            if (BaseLocationActivity.npcCode == 0) {
                activity.showWaitingDialog(false);
                if (sun >= 3) {
                    // ToastUtil.show("无法获取您的位置，请走到开阔地带重试");
                    activity.dismissWaitingDialog();
                    sun = 0;
                } else {
                    Message msg = Message.obtain();
                    msg.what = 0;
                    Bundle args = new Bundle();
                    args.putString("phone", phoneNum);
                    args.putString("pswd", password);
                    msg.setData(args);
                    handler.sendMessageDelayed(msg, 1000);
                    //                    handler.sendEmptyMessageDelayed(0, 1000);//发送消息
                    sun++;
                    return;
                }
            } else {
                activity.dismissWaitingDialog();
            }
            activity.showWaitingDialog(false);
            String encryptPassword = new String(EncryptUtils.encryptAES2Base64(password.getBytes(), AES_KEY.getBytes(), AES_TRANSFORM, AES_IV.getBytes()));
            JMainHttpUtil.loginByPassword(phoneNum, encryptPassword, BaseLocationActivity.npcCode, new JHttpCallback() {
                @Override
                public void onSuccess(int code, String msg, String info) {
                    activity.dismissWaitingDialog();
                    onMsgSuccess(phoneNum, code, msg, info);
                }

                @Override
                public void onError(Response<JJsonBean> response) {
                    activity.dismissWaitingDialog();
                    super.onError(response);
                    ToastUtil.show(response.getException().getMessage());
                }
            });
        }
    }

    private void onMsgSuccess(String phoneNum, int code, String msg, String info) {
        if (code == 200 && !info.equals("")) {
            LoginBean loginBean = GsonUtil.gsonToBean(info, LoginBean.class);
            BaseLocationActivity.parentSdNo = loginBean.getParentSdNo();
            SpUtil.getInstance().setStringValue(SpUtil.TX_IM_USER_SIGN, loginBean.getUsersig());
            MobclickAgent.onProfileSignIn(Constants.MOB_PHONE, loginBean.getUid());
            EventBus.getDefault().post(new LoginSuccessEvent());
            CommonAppConfig.getInstance().setLoginInfo(loginBean.getUid(), loginBean.getAccessToken(), true);
            SpUtil.getInstance().setStringValue(SpUtil.JAVA_TOKEN, loginBean.getTokenType() + " " + loginBean.getAccessToken());
            isFirstLogin(loginBean.getNikeName());
            SpUtil.getInstance().setStringValue(SpUtil.SP_MOBILE, phoneNum);
            // OneKeyLoginManager.getInstance().finishAuthActivity();
        } else {
            ToastUtil.show(msg);
        }
    }

    private void isFirstLogin(String name) {
        if ("".equals(name)) {
            //进入填写资料页面
            LoginGenderAgeActivity.forward(2);
        } else {
            //进入首页
            getBaseUserInfo();
        }
    }

    /**
     * 获取用户信息
     */
    private void getBaseUserInfo() {
        MainHttpUtil.getBaseInfo(new CommonCallback<UserBean>() {
            @Override
            public void callback(UserBean bean) {
                MainActivity.Companion.forward(mContext, mFirstLogin);
            }
        });
    }


    private final MyHandler handler = new MyHandler(this);

    public static class MyHandler extends Handler {

        private final WeakReference<LauncherLoginFragment> fragmentWeakReference;

        public MyHandler(LauncherLoginFragment launcherLoginFragment) {
            fragmentWeakReference = new WeakReference<>(launcherLoginFragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LauncherLoginFragment launcherLoginFragment = fragmentWeakReference.get();
            if (launcherLoginFragment == null) {
                return;
            }
            Bundle data = msg.getData();
            String phoneNum = data.getString("phone");
            String password = data.getString("pswd");
            launcherLoginFragment.doLoginByPassword(phoneNum, password);
        }
    }

    //    private final Handler handler = new Handler() {
    //        //接收handler发送的message
    //        @Override
    //        public void handleMessage(Message msg) {
    //            super.handleMessage(msg);
    //            doLoginByPassword();
    //        }
    //    };
    int sun = 0;

}